package org.nestor.demo.client;


import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;
import org.nestor.demo.protobuf.ChatMessage;
import org.nestor.demo.protobuf.ChatServiceGrpc;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 双向流示例
 */
public class ChatClient {

    public static void main(String[] args) throws InterruptedException {
        ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 50051)
                .usePlaintext()
                .build();

        ChatServiceGrpc.ChatServiceStub asyncStub = ChatServiceGrpc.newStub(channel);

        CountDownLatch latch = new CountDownLatch(1);

        StreamObserver<ChatMessage> requestObserver = asyncStub.chat(new StreamObserver<ChatMessage>() {
            @Override
            public void onNext(ChatMessage message) {
                // 收到服务端的回应
                System.out.println(Thread.currentThread().getName() + ":Server says: " + message.getMessage());
            }

            @Override
            public void onError(Throwable t) {
                System.err.println("Error from server: " + t.getMessage());
                latch.countDown();
            }

            @Override
            public void onCompleted() {
                System.out.println("Chat completed.");
                latch.countDown();
            }
        });

        // 模拟发送几条消息
        for (int i = 1; i <= 3; i++) {
            ChatMessage message = ChatMessage.newBuilder()
                    .setUser("ClientUser")
                    .setMessage("Hello " + i)
                    .build();
            requestObserver.onNext(message);

            Thread.sleep(1000); // 模拟每秒发一条
        }

        // 通知服务端，客户端发送完毕
        requestObserver.onCompleted();

        // 等待直到通话结束
        latch.await(5, TimeUnit.SECONDS);

        channel.shutdownNow();
    }
}
